import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { authService } from '@/api/authService'
import { adminService } from '@/api/adminService'
import type { User, Admin, LoginRequest, RegisterRequest } from '@/types'
import { ElMessage } from 'element-plus'
import { createLogger } from '@/utils/logger'
import { extractErrorMessage } from '@/utils/errorHandler'

const authLogger = createLogger('Auth')

export const useAuthStore = defineStore('auth', () => {
  // 注意：此Store已迁移到新的分离式登录系统
  // 新的登录入口：/auth (选择页面) -> 选择登录方式
  // 已弃用：开发模式变量 - 不再需要
  // const isDev = import.meta.env.DEV
  // 状态
  const user = ref<User | null>(null)
  const admin = ref<Admin | null>(null)
  const token = ref<string | null>(null)
  const isAuthenticated = ref(false)
  const isAdmin = ref(false)
  const loading = ref(false)
  const error = ref<string | null>(null)

  // 计算属性
  const currentUser = computed(() => user.value || admin.value)
  const userRole = computed(() => {
    if (admin.value) return 'admin'
    if (user.value) return 'user'
    return 'guest'
  })

  // 用户认证方法
  const loginUser = async (credentials: LoginRequest) => {
    loading.value = true
    error.value = null
    try {
      const response = await authService.login(credentials)
      const { token: userToken, user: userData } = response.data.data

      // 保存认证信息
      token.value = userToken
      user.value = userData
      admin.value = null
      isAuthenticated.value = true
      isAdmin.value = false

      // 保存到本地存储
      localStorage.setItem('token', userToken)
      localStorage.setItem('user', JSON.stringify(userData))
      localStorage.setItem('userType', 'user')

      ElMessage.success('登录成功')
      return { success: true }
    } catch (error: unknown) {
      // 使用统一的错误处理工具提取错误消息
      const errorMessage = extractErrorMessage(error, '登录失败')
      
      // 设置错误状态，供UI组件显示
      error.value = errorMessage
      ElMessage.error(errorMessage)
      return { success: false, error: errorMessage }
    } finally {
      loading.value = false
    }
  }

  // 已弃用：管理员认证方法 - 已迁移到新的分离式登录系统
  // 新的管理员登录逻辑在 AdminLogin.vue 组件中实现

  // 用户注册
  const registerUser = async (userData: RegisterRequest) => {
    loading.value = true
    error.value = null
    try {
      await authService.register(userData)
      ElMessage.success('注册成功，请登录')
      return { success: true }
    } catch (error: unknown) {
      // 使用统一的错误处理工具提取错误消息
      const errorMessage = extractErrorMessage(error, '注册失败')
      
      // 设置错误状态，供UI组件显示
      error.value = errorMessage
      ElMessage.error(errorMessage)
      return { success: false, error: errorMessage }
    } finally {
      loading.value = false
    }
  }

  // 登出
  const logout = async () => {
    try {
      if (isAdmin.value) {
        await adminService.logout()
      } else if (user.value) {
        await authService.logout()
      }
    } catch (error: unknown) {
      console.error('登出失败:', error)
    } finally {
      // 清除所有认证信息
      clearAuth()
      ElMessage.success('已退出登录')
    }
  }

  // 清除认证信息
  const clearAuth = () => {
    user.value = null
    admin.value = null
    token.value = null
    isAuthenticated.value = false
    isAdmin.value = false
    error.value = null

    localStorage.removeItem('token')
    localStorage.removeItem('user')
    localStorage.removeItem('admin')
    localStorage.removeItem('userType')
  }

  // 检查认证状态
  const checkAuth = async () => {
    const userType = localStorage.getItem('userType')
    const storedToken = localStorage.getItem('token')

    if (!userType) {
      clearAuth()
      return false
    }

    try {
      if (userType === 'admin') {
        // 管理员：需要 token 进行校验
        if (!storedToken) {
          clearAuth()
          return false
        }
        
        try {
          const response = await adminService.verifyToken()
          if (response.data.data) {
            const storedAdmin = localStorage.getItem('admin')
            if (storedAdmin) {
              admin.value = JSON.parse(storedAdmin)
              isAuthenticated.value = true
              isAdmin.value = true
              token.value = storedToken
              return true
            }
          }
        } catch (error) {
          console.error('管理员 token 验证失败:', error)
          clearAuth()
          return false
        }
      } else if (userType === 'user') {
        // 普通用户：要求 token
        if (!storedToken) {
          clearAuth()
          return false
        }
        
        try {
          const response = await authService.verifyToken()
          if (response.data.data) {
            const storedUser = localStorage.getItem('user')
            if (storedUser) {
              user.value = JSON.parse(storedUser)
              token.value = storedToken
              isAuthenticated.value = true
              isAdmin.value = false
              return true
            }
          }
        } catch (error) {
          console.error('用户 token 验证失败:', error)
          clearAuth()
          return false
        }
      }
    } catch (error) {
      authLogger.error('Token验证失败:', error)
    }

    clearAuth()
    return false
  }

  // 获取用户信息
  const fetchUserProfile = async () => {
    if (!isAuthenticated.value || isAdmin.value) return

    try {
      const response = await authService.getProfile()
      user.value = response.data.data
      localStorage.setItem('user', JSON.stringify(user.value))
    } catch (error: unknown) {
      console.error('获取用户信息失败:', error)
      // 类型安全的错误处理
      if (error && typeof error === 'object' && 'code' in error && error.code === 401) {
        clearAuth()
      }
    }
  }

  // 更新用户信息
  const updateUserProfile = async (userData: Partial<User>) => {
    if (!isAuthenticated.value || isAdmin.value) return

    try {
      const response = await authService.updateProfile(userData)
      user.value = response.data.data
      localStorage.setItem('user', JSON.stringify(user.value))
      ElMessage.success('个人信息更新成功')
      return { success: true }
    } catch (error: unknown) {
      const message = error instanceof Error ? error.message : '更新失败'
      ElMessage.error(message)
      return { success: false, error: message }
    }
  }

  // 修改密码
  const changePassword = async (oldPassword: string, newPassword: string) => {
    if (!isAuthenticated.value || isAdmin.value) return

    try {
      await authService.changePassword(oldPassword, newPassword)
      ElMessage.success('密码修改成功')
      return { success: true }
    } catch (error: unknown) {
      const message = error instanceof Error ? error.message : '密码修改失败'
      ElMessage.error(message)
      return { success: false, error: message }
    }
  }

  // 权限检查
  const hasPermission = (permission: string) => {
    if (!isAuthenticated.value) return false

    if (isAdmin.value) {
      // 管理员拥有所有权限
      return true
    }

    // 用户权限检查（可以根据实际需求扩展）
    type UserWithPermissions = import('@/types').User & { permissions?: string[] }
    const userPermissions = (user.value as UserWithPermissions | null)?.permissions ?? []
    return userPermissions.includes(permission)
  }

  // 初始化认证状态
  const setAdminAuth = (adminData: { username: string; adminRole?: string; adminRoleId?: number; id?: number }, adminToken?: string) => {
    admin.value = adminData as unknown as Admin
    user.value = null
    isAuthenticated.value = true
    isAdmin.value = true
    if (adminToken) {
      token.value = adminToken
      localStorage.setItem('token', adminToken)
    }
    localStorage.setItem('userType', 'admin')
    localStorage.setItem('admin', JSON.stringify(adminData))
  }

  const initAuth = async () => {
    await checkAuth()
  }

  return {
    // 状态
    user,
    admin,
    token,
    isAuthenticated,
    isAdmin,
    loading,
    error,
    // 兼容别名
    isLoading: computed(() => loading.value),
    isLoggedIn: computed(() => isAuthenticated.value),

    // 计算属性
    currentUser,
    userRole,

    // 方法
    loginUser,
    // 已弃用：loginAdmin - 已迁移到新的分离式登录系统
    // loginAdmin,
    registerUser,
    // 兼容别名方法
    login: loginUser,
    register: registerUser,
    logout,
    clearAuth,
    checkAuth,
    fetchUserProfile,
    updateUserProfile,
    changePassword,
    hasPermission,
    setAdminAuth,
    initAuth,
  }
})
